<template>
  <PageWrapper>
    <a-card>
      <div class="container contents">
        <a-row>
          <a-col :span="18"></a-col>
          <a-col :span="6">
            <a-range-picker
              v-model="selectDate"
              :showTime="true"
              format="YYYY/MM/DD HH:mm:ss"
              :ranges="timeRanges"
              @ok="selectDateOk"
            />
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-card>
              <iframe title="topReqRateIframe" class="panelIframe" :src="topReqRateIframeUrl" frameborder="0"></iframe>
            </a-card>
          </a-col>
          <a-col :span="8">
            <a-card>
              <iframe
                title="topServerErrRateIframe"
                class="panelIframe"
                :src="topServerErrRateIframeUrl"
                frameborder="0"
              ></iframe>
            </a-card>
          </a-col>
          <a-col :span="8">
            <a-card>
              <iframe
                title="topRespLatencyIframe"
                class="panelIframe"
                :src="topRespLatencyIframeUrl"
                frameborder="0"
              ></iframe>
            </a-card>
          </a-col>
        </a-row>
        <a-card>
          <a-input
            v-model="input"
            placeholder="请输入应用名"
            @input="handleInput"
            @clear="handleClear"
            style="width: 30%"
            clearable
          >
          </a-input>
          <a-table :columns="tableColumns" :data-source="tableData" rowKey="id">
            <template #bodyCell="{ record, column }">
              <template v-if="column.dataIndex === 'clientName'">
                <a-button type="link" @click="click(record.client)">{{ record.client.name }}</a-button>
              </template>
              <template v-else-if="column.dataIndex === 'serverName'">
                <a-button type="link" @click="click(record.server)">{{ record.server.name }}</a-button>
              </template>
              <template v-else>
                {{ record[column.dataIndex] || '-' }}
              </template>
            </template>
          </a-table>
        </a-card>
        <a-drawer
          :title="drawerTitle"
          :visible="drawer"
          @close="handleClose"
          :width="drawerWidth"
          :destroyOnClose="true"
        >
          <appDetail
            :isShow="showAppDetail"
            :machine_id="machine_id"
            :podId="podId"
            :tgid="tgid"
            :windowWidth="drawerWidth"
            :objectType="objectType"
            :objectId="objectId"
            :startTimestamp="startTimestamp"
            :endTimestamp="endTimestamp"
          />
        </a-drawer>
      </div>
    </a-card>
  </PageWrapper>
</template>

<script>
import appDetail from './appDetail.vue'
import { timeRanges } from './components'
import {
  getTopReqRateObjectList,
  getTopServerErrRateObjectList,
  getTopRespLatencyObjectList,
  getCSTrafficList,
} from '@/views/app/req'
import dayjs from 'dayjs'
import { api } from '@/api'
import PageWrapper from '@/components/PageWrapper.vue'

export default {
  name: 'TrafficRelation',
  components: { PageWrapper, appDetail },
  data() {
    return {
      tableData: [],
      tempData: [],
      input: '',
      drawer: false,
      machine_id: '',
      podId: '',
      tgid: '',
      drawerTitle: '',
      drawerWidth: 0,
      direction: 'rtl',
      showAppDetail: false,
      objectId: '',
      objectType: '',
      tableColumns: [
        {
          title: '客户端应用',
          dataIndex: 'clientName',
          scopedSlots: { customRender: 'clientName' },
        },
        {
          title: '服务端应用',
          dataIndex: 'serverName',
          scopedSlots: { customRender: 'serverName' },
        },
        {
          title: '请求速率',
          dataIndex: 'clientReqRate',
          key: 'reqRate',
        },
        {
          title: '服务端异常比例',
          dataIndex: 'serverExceptionRate',
          key: 'serverExceptionRate',
        },
        {
          title: '请求时延',
          dataIndex: 'clientReqLatency',
          key: 'reqLatency',
        },
        {
          title: '响应时延',
          dataIndex: 'serverRespLatency',
          key: 'respLatency',
        },
        {
          title: 'TCP时延',
          dataIndex: 'tcpLatency',
          key: 'tcpLatency'
        }
      ],
      selectDate: [],
      timeRanges: timeRanges,
      topReqRateIframeUrl: '',
      topServerErrRateIframeUrl: '',
      topRespLatencyIframeUrl: '',
      startTimestamp: '',
      endTimestamp: '',
      grafanaServerAddr: '',
    }
  },
  computed: {},
  created() {},
  mounted() {
    this.initGrafanaServerAddr()
    var currTimestamp = Date.now()
    var fromTimestamp = currTimestamp - 1000 * 60 * 5
    this.selectDate.push(dayjs(fromTimestamp))
    this.selectDate.push(dayjs(currTimestamp))
    this.initTopPanels()
    this.initTable()
  },
  updated() {},
  methods: {
    async initTable() {
      this.tableData = await getCSTrafficList({
        startTime: this.selectDate[0].valueOf() / 1000,
        endTime: this.selectDate[1].valueOf() / 1000,
        queryKeyword: this.input,
      })
      console.log('tabledata', this.tableData)
    },
    async initGrafanaServerAddr() {
      // const [_, res] = await api.getGrafanaServerAddr()

      this.grafanaServerAddr = '/grafanaweb';
    },
    handleInput(val) {
      this.initTable()
    },
    handleClear() {},
    click(e) {
      this.drawer = true
      this.drawerWidth = window.innerWidth * 0.865
      this.showAppDetail = true
      this.drawerTitle = `${e.name} 应用详情`
      this.machine_id = e.machine_id.substr(0, 36)
      this.tgid = e.tgid
      this.podId = e.pod_id
      this.objectType = e.type
      this.objectId = e.objectId
      this.startTimestamp = this.selectDate[0].valueOf()
      this.endTimestamp = this.selectDate[1].valueOf()
    },
    handleClose() {
      this.drawer = false
    },
    selectDateOk(e) {
      this.initTopPanels()
      this.initTable()
    },
    getQueryPattern(item) {
      var queryPattern = ''
      switch (item.type) {
        case 'pod':
          queryPattern = `&var-pod_id=${item.objectId}`
          break
        case 'container':
          queryPattern = `&var-container_id=${item.objectId}`
          break
        case 'proc':
          queryPattern = `&var-tgid=${item.objectId}`
          break
      }
      return queryPattern
    },
    getGapQueryStr(querypattern) {
      var res = ''
      if (querypattern.indexOf('pod_id') === -1) {
        res += '&var-pod_id=-1'
      }
      if (querypattern.indexOf('container_id') === -1) {
        res += '&var-container_id=-1'
      }
      if (querypattern.indexOf('tgid') === -1) {
        res += '&var-tgid=-1'
      }
      return res
    },
    async initTopPanels() {
      var queryPattern1 = ''
      var queryPattern2 = ''
      var queryPattern3 = ''
      var item
      const startTimestamp = this.selectDate[0].valueOf()
      const endTimestamp = this.selectDate[1].valueOf()
      const param = {
        startTimestamp: startTimestamp / 1000,
        endTimestamp: endTimestamp / 1000,
      }
      var topReqRateObjectList = await getTopReqRateObjectList(param)
      var topServerErrRateObjectList = await getTopServerErrRateObjectList(param)
      var topRespLatencyObjectList = await getTopRespLatencyObjectList(param)

      for (item of topReqRateObjectList) {
        queryPattern1 += this.getQueryPattern(item)
      }
      queryPattern1 += this.getGapQueryStr(queryPattern1)

      for (item of topServerErrRateObjectList) {
        queryPattern2 += this.getQueryPattern(item)
      }
      queryPattern2 += this.getGapQueryStr(queryPattern2)

      for (item of topRespLatencyObjectList) {
        queryPattern3 += this.getQueryPattern(item)
      }
      queryPattern3 += this.getGapQueryStr(queryPattern3)

      this.topReqRateIframeUrl = `${this.grafanaServerAddr}/d-solo/xvSeLIKIz/appdetail-appaccesspanels?orgId=1
      ${queryPattern1}&from=${startTimestamp}&to=${endTimestamp}&orgId=1&panelId=167&theme=light`
      this.topServerErrRateIframeUrl = `${this.grafanaServerAddr}/d-solo/xvSeLIKIz/appdetail-appaccesspanels?orgId=1
      ${queryPattern2}&from=${startTimestamp}&to=${endTimestamp}&orgId=1&panelId=169&theme=light`
      this.topRespLatencyIframeUrl = `${this.grafanaServerAddr}/d-solo/xvSeLIKIz/appdetail-appaccesspanels?orgId=1
      ${queryPattern3}&from=${startTimestamp}&to=${endTimestamp}&orgId=1&panelId=171&theme=light`
    },
  },
}
</script>

<style scoped lang="less">
::v-deep {
  .panelTitle {
    width: 100%;
    text-align: center;
    margin-bottom: 5px;
  }
  .panelIframe {
    width: 100%;
    height: 200px;
  }
  .ant-card-body {
    padding-bottom: 0px;
  }
}
</style>
